package com.lightsh.reflect;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class ProxyHelper {

	/**
	 * 生成interface对应的代理对象
	 * @param interfaceName	接口全名称
	 * @param handler			需要实现接口invoke的handler
	 * @return
	 * @throws Exception
	 */
	public static final Object generateProxyHandler(String interfaceName, InvocationHandler handler) throws Exception{
		Class<?> interfaceClass = Class.forName(interfaceName);		
		return generateProxyHandler(interfaceClass, handler);
	}
	private static final Object generateProxyHandler(Class<?> interfaceClass, InvocationHandler handler) throws Exception{
		return Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[]{interfaceClass}, handler);
	}
	
	/**
	 * 该方法类似setOnclickListener()方法的代理
	 * @param obj					需要设置接口的对象
	 * @param methodName			设置接口的方法名称
	 * @param interfaceName		接口的全名称
	 * @param handler				需要实现接口invoke的handler
	 * @return
	 * @throws Exception
	 */
	public static final Object invokeByProxy(Object obj, String methodName, String interfaceName, InvocationHandler handler) throws Exception{
		Class<?> interfaceClass = Class.forName(interfaceName);
		Object proxy = generateProxyHandler(interfaceClass, handler);
		return ReflectHelper.invoke(obj, methodName, new Class<?>[]{interfaceClass}, new Object[]{proxy});
	}
}
